/**
 * Markdown到JSON转换器
 * 用于将Vue.js学习内容的Markdown文件转换为Neo4j知识图谱的JSON格式
 */

const fs = require('fs');
const path = require('path');
const marked = require('marked');

class MarkdownToJsonConverter {
    constructor() {
        this.knowledgeGraph = {
            metadata: {
                version: '3.0',
                created: new Date().toISOString().split('T')[0],
                description: 'Vue.js学习知识图谱数据结构 - 四层架构支持个性化学习',
                total_levels: 0,
                total_topics: 0,
                total_subtopics: 0,
                total_knowledge_points: 0,
                total_concepts: 0,
                total_quizzes: 0,
                total_students: 0
            },
            levels: [],
            topics: [],
            subtopics: [],
            knowledge_points: [],
            concepts: [],
            quizzes: [],
            students: [],
            assessments: [],
            learning_paths: [],
            relationships: []
        };
        
        this.levelMapping = {
            '1 前端技术.md': { id: 'basic', name: '基础层', order: 1 },
            '2 开发环境.md': { id: 'basic', name: '基础层', order: 1 },
            '3 过渡层.md': { id: 'intermediate', name: '进阶层', order: 2 },
            '4-Vue模板指令.md': { id: 'intermediate', name: '进阶层', order: 2 },
            '第1章_前端技术绪论.md': { id: 'basic', name: '基础层', order: 1 },
            '第1章_前端技术基础.md': { id: 'basic', name: '基础层', order: 1 }
        };
        
        this.difficultyMapping = {
            '前端技术': 1,
            '开发环境': 2,
            '过渡层': 3,
            '模板指令': 4,
            '前端技术绪论': 1,
            '前端技术基础': 1
        };
    }

    /**
     * 解析Markdown文件
     */
    parseMarkdownFile(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf8');
            const fileName = path.basename(filePath);
            const tokens = marked.lexer(content);
            
            console.log(`正在解析文件: ${fileName}`);
            
            const topic = this.extractTopicFromTokens(tokens, fileName);
            if (topic) {
                this.knowledgeGraph.topics.push(topic);
                console.log(`成功提取知识点: ${topic.name}`);
            }
            
            // 解析四层架构内容
            this.parseMarkdownContent(content, fileName);
            
        } catch (error) {
            console.error(`解析文件 ${filePath} 时出错:`, error.message);
        }
    }

    /**
     * 解析Markdown内容支持四层架构
     */
    parseMarkdownContent(content, fileName) {
        const lines = content.split('\n');
        const levelInfo = this.levelMapping[fileName];
        if (!levelInfo) return;
        
        let currentTopic = null;
        let currentSubtopic = null;
        let currentKnowledgePoint = null;
        let currentConcept = null;
        let contentBuffer = [];
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            if (line.startsWith('# ')) {
                // 第1层级：Topic
                this.saveCurrentContent(currentConcept || currentKnowledgePoint, contentBuffer);
                contentBuffer = [];
                
                const topicName = line.substring(2).trim().replace(/^\d+\s*/, '').trim();
                currentTopic = this.knowledgeGraph.topics.find(t => t.name === topicName);
                currentSubtopic = null;
                currentKnowledgePoint = null;
                currentConcept = null;
                
            } else if (line.startsWith('## ')) {
                // 第2层级：Subtopic
                this.saveCurrentContent(currentConcept || currentKnowledgePoint, contentBuffer);
                contentBuffer = [];
                
                if (currentTopic) {
                    const subtopicName = line.substring(3).trim();
                    const subtopicId = `${currentTopic.id}-${this.generateId(subtopicName)}`;
                    
                    currentSubtopic = {
                        id: subtopicId,
                        name: subtopicName,
                        parent_topic: currentTopic.id,
                        content: '',
                        key_points: [],
                        difficulty: 'beginner'
                    };
                    
                    this.knowledgeGraph.subtopics.push(currentSubtopic);
                    
                    // 创建关系
                    this.knowledgeGraph.relationships.push({
                        type: 'PART_OF',
                        from: subtopicId,
                        to: currentTopic.id,
                        fromLabel: 'Subtopic',
                        toLabel: 'Topic'
                    });
                }
                currentKnowledgePoint = null;
                currentConcept = null;
                
            } else if (line.startsWith('### ')) {
                // 第3层级：KnowledgePoint
                this.saveCurrentContent(currentConcept || currentKnowledgePoint, contentBuffer);
                contentBuffer = [];
                
                if (currentSubtopic) {
                    const knowledgePointName = line.substring(4).trim();
                    const knowledgePointId = `${currentSubtopic.id}-kp-${this.generateId(knowledgePointName)}`;
                    
                    currentKnowledgePoint = {
                        id: knowledgePointId,
                        name: knowledgePointName,
                        parent_subtopic: currentSubtopic.id,
                        content: '',
                        key_points: [],
                        examples: [],
                        difficulty: 'beginner'
                    };
                
                    this.knowledgeGraph.knowledge_points.push(currentKnowledgePoint);
                    
                    // 添加知识点与子主题的关系
                    this.knowledgeGraph.relationships.push({
                        type: 'PART_OF',
                        from: knowledgePointId,
                        to: currentSubtopic.id,
                        fromLabel: 'KnowledgePoint',
                        toLabel: 'Subtopic'
                    });
                }
                currentConcept = null;
                
            } else if (line.startsWith('#### ')) {
                // 第4层级 - Concept
                this.saveCurrentContent(currentConcept, contentBuffer);
                contentBuffer = [];
                
                const conceptName = line.substring(5).trim();
                const conceptId = currentKnowledgePoint ? 
                    `${currentKnowledgePoint.id}-concept-${this.generateId(conceptName)}` : 
                    `concept-${this.generateId(conceptName)}`;
                
                currentConcept = {
                    id: conceptId,
                    name: conceptName,
                    parent_knowledge_point: currentKnowledgePoint ? currentKnowledgePoint.id : null,
                    definition: '',
                    content: '',
                    key_points: [],
                    examples: [],
                    related_concepts: []
                };
                
                this.knowledgeGraph.concepts.push(currentConcept);
                
                // 添加概念与知识点的关系
                if (currentKnowledgePoint) {
                    this.knowledgeGraph.relationships.push({
                        type: 'PART_OF',
                        from: conceptId,
                        to: currentKnowledgePoint.id,
                        fromLabel: 'Concept',
                        toLabel: 'KnowledgePoint'
                    });
                }
                
            } else if (line.startsWith('- ') || line.startsWith('* ')) {
                // 列表项 - 添加到当前概念的关键点
                const listItem = line.substring(2).trim();
                if (listItem.length > 0) {
                    if (currentConcept) {
                        currentConcept.key_points.push(listItem);
                    } else if (currentKnowledgePoint) {
                        currentKnowledgePoint.key_points.push(listItem);
                    }
                }
                
            } else if (line.length > 0) {
                // 收集内容
                contentBuffer.push(line);
            }
        }
        
        // 保存最后的内容
        if (currentConcept) {
            this.saveCurrentContent(currentConcept, contentBuffer);
        } else {
            this.saveCurrentContent(currentKnowledgePoint, contentBuffer);
        }
    }

    /**
     * 保存当前内容到知识点或概念
     */
    saveCurrentContent(item, contentBuffer) {
        if (item && contentBuffer.length > 0) {
            const content = contentBuffer.join('\n').trim();
            item.content = content;
            
            // 如果是概念，设置definition
            if (item.hasOwnProperty('definition')) {
                item.definition = content;
            }
            
            // 如果是知识点（不是概念），提取key_points
            if (item.hasOwnProperty('key_points') && !item.hasOwnProperty('parent_knowledge_point')) {
                const extractedPoints = this.extractKeyPoints(content);
                if (extractedPoints.length > 0) {
                    item.key_points = item.key_points.concat(extractedPoints);
                }
            }
        }
    }

    /**
     * 生成ID
     */
    generateId(text) {
        return text.toLowerCase()
            .replace(/[^a-z0-9\u4e00-\u9fa5]/g, '-')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '');
    }

    /**
     * 提取关键点
     */
    extractKeyPoints(content) {
        const points = [];
        const lines = content.split('\n');
        
        for (const line of lines) {
            const trimmed = line.trim();
            if (trimmed.startsWith('- ') || trimmed.startsWith('* ')) {
                points.push(trimmed.substring(2).trim());
            }
        }
        
        return points;
    }

    /**
     * 从tokens中提取知识点信息
     */
    extractTopicFromTokens(tokens, fileName) {
        const levelInfo = this.levelMapping[fileName];
        if (!levelInfo) {
            console.warn(`未找到文件 ${fileName} 的层级映射`);
            return null;
        }

        const topicId = this.generateTopicId(fileName);
        const topic = {
            id: topicId,
            name: this.extractTopicName(tokens),
            level: levelInfo.id,
            difficulty: this.getDifficultyFromFileName(fileName),
            description: this.extractDescription(tokens),
            prerequisites: this.extractPrerequisites(fileName),
            estimated_hours: this.estimateHours(tokens),
            status: 'to-learn', // 默认状态：待学习
            lastLearned: null,
            completionRate: 0,
            resources: [{
                id: `resource_${topicId}`,
                type: 'markdown',
                title: this.extractTopicName(tokens),
                path: fileName,
                section: '全文',
                completionRequired: true,
                status: 'available'
            }]
        };

        // 注释：subtopics现在通过parseMarkdownContent方法处理，避免重复创建

        // 特殊处理Vue指令文件
        if (fileName === '4-Vue模板指令.md') {
            topic.directives = this.extractVueDirectives(tokens);
            topic.projects = this.extractProjects(tokens);
        }

        // 为每个知识点生成对应的Quiz
        const quiz = this.generateQuizForTopic(topic);
        this.knowledgeGraph.quizzes.push(quiz);
        
        // 添加Topic到Quiz的关系
        this.knowledgeGraph.relationships.push({
            type: 'HAS_QUIZ',
            from: topic.id,
            to: quiz.id,
            fromLabel: 'Topic',
            toLabel: 'Quiz'
        });

        return topic;
    }

    /**
     * 生成知识点ID
     */
    generateTopicId(fileName) {
        const idMapping = {
            '1 前端技术.md': 'frontend-basics',
            '2 开发环境.md': 'development-environment',
            '3 过渡层.md': 'vue-transition',
            '4-Vue模板指令.md': 'vue-template-directives',
            '第1章_前端技术绪论.md': 'frontend-introduction',
            '第1章_前端技术基础.md': 'frontend-technology-basics'
        };
        return idMapping[fileName] || fileName.replace(/\s+/g, '-').replace('.md', '').toLowerCase();
    }

    /**
     * 提取知识点名称
     */
    extractTopicName(tokens) {
        const firstHeading = tokens.find(token => token.type === 'heading' && token.depth === 1);
        if (firstHeading) {
            return firstHeading.text.replace(/^\d+\s*/, '').trim();
        }
        return '未命名知识点';
    }

    /**
     * 提取描述信息
     */
    extractDescription(tokens) {
        // 查找第一个段落作为描述
        const firstParagraph = tokens.find(token => token.type === 'paragraph');
        if (firstParagraph) {
            return firstParagraph.text.substring(0, 200) + (firstParagraph.text.length > 200 ? '...' : '');
        }
        return '';
    }

    /**
     * 根据文件名获取难度
     */
    getDifficultyFromFileName(fileName) {
        for (const [key, difficulty] of Object.entries(this.difficultyMapping)) {
            if (fileName.includes(key)) {
                return difficulty;
            }
        }
        return 1;
    }

    /**
     * 提取前置依赖
     */
    extractPrerequisites(fileName) {
        const prerequisites = {
            '1 前端技术.md': [],
            '2 开发环境.md': ['frontend-basics'],
            '3 过渡层.md': ['frontend-basics', 'development-environment'],
            '4-Vue模板指令.md': ['vue-transition'],
            '第1章_前端技术绪论.md': [],
            '第1章_前端技术基础.md': []
        };
        return prerequisites[fileName] || [];
    }

    /**
     * 估算学习时长
     */
    estimateHours(tokens) {
        const textLength = tokens
            .filter(token => token.type === 'paragraph' || token.type === 'text')
            .reduce((total, token) => total + (token.text ? token.text.length : 0), 0);
        
        // 基于文本长度估算（每1000字符约需15分钟）
        return Math.max(1, Math.round(textLength / 1000 * 0.25));
    }

    // 已删除extractSubtopics和generateSubtopicId方法
    // 现在使用parseMarkdownContent方法统一处理四级层次结构

    /**
     * 提取Vue指令信息
     */
    extractVueDirectives(tokens) {
        const directives = [];
        
        // 查找表格token
        const tableToken = tokens.find(token => token.type === 'table');
        if (!tableToken) return directives;
        
        // 解析表格数据
        for (const row of tableToken.rows) {
            if (row.length >= 3) {
                const directive = {
                    id: this.extractDirectiveId(row[1]),
                    name: row[1].replace(/,.*$/, '').trim(), // 移除简写部分
                    description: row[2],
                    difficulty: this.calculateDirectiveDifficulty(row[1]),
                    examples: this.extractDirectiveExamples(row[2])
                };
                
                // 提取简写形式
                const shorthandMatch = row[1].match(/简写\s*([#@:])/);  
                if (shorthandMatch) {
                    directive.shorthand = shorthandMatch[1];
                }
                
                directives.push(directive);
            }
        }
        
        return directives;
    }

    /**
     * 提取指令ID
     */
    extractDirectiveId(nameText) {
        const match = nameText.match(/v-[\w-]+/);
        return match ? match[0] : nameText.toLowerCase().replace(/\s+/g, '-');
    }

    /**
     * 计算指令难度
     */
    calculateDirectiveDifficulty(nameText) {
        const complexDirectives = ['v-for', 'v-model', 'v-on'];
        const mediumDirectives = ['v-if', 'v-bind', 'v-show'];
        
        if (complexDirectives.some(d => nameText.includes(d))) return 4;
        if (mediumDirectives.some(d => nameText.includes(d))) return 3;
        return 2;
    }

    /**
     * 提取指令示例
     */
    extractDirectiveExamples(description) {
        const examples = [];
        const codeMatches = description.match(/`([^`]+)`/g);
        
        if (codeMatches) {
            codeMatches.forEach(match => {
                const code = match.replace(/`/g, '');
                examples.push({
                    code: code,
                    description: `${code}的使用示例`
                });
            });
        }
        
        return examples;
    }

    /**
     * 提取项目信息
     */
    extractProjects(tokens) {
        const projects = [];
        
        // 查找项目相关的列表项
        for (const token of tokens) {
            if (token.type === 'list') {
                for (const item of token.items) {
                    if (item.text.includes('改造') || item.text.includes('项目')) {
                        projects.push({
                            id: this.generateProjectId(item.text),
                            name: item.text,
                            description: `使用Vue指令实现${item.text}`,
                            required_directives: this.inferRequiredDirectives(item.text)
                        });
                    }
                }
            }
        }
        
        return projects;
    }

    /**
     * 生成项目ID
     */
    generateProjectId(text) {
        return text.toLowerCase()
            .replace(/[^a-z0-9]/g, '-')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '');
    }

    /**
     * 推断所需指令
     */
    inferRequiredDirectives(projectText) {
        const directives = [];
        
        if (projectText.includes('登录')) {
            directives.push('v-model', 'v-on', 'v-if');
        }
        if (projectText.includes('待办') || projectText.includes('列表')) {
            directives.push('v-for', 'v-model', 'v-on', 'v-bind');
        }
        
        return directives;
    }

    /**
     * 初始化层级数据
     */
    initializeLevels() {
        const levels = [
            {
                id: 'basic',
                name: '基础层',
                order: 1,
                description: '前端基础概念、开发环境配置',
                color: '#4CAF50'
            },
            {
                id: 'intermediate',
                name: '进阶层',
                order: 2,
                description: 'Vue框架核心概念、模板语法',
                color: '#FF9800'
            },
            {
                id: 'advanced',
                name: '项目实践层',
                order: 3,
                description: '组件开发、路由管理、项目实战',
                color: '#F44336'
            }
        ];
        
        this.knowledgeGraph.levels = levels;
        this.knowledgeGraph.metadata.total_levels = levels.length;
    }

    /**
     * 生成示例学生数据
     */
    generateSampleStudents() {
        const students = [
            {
                id: 'student_001',
                studentId: 'S001',
                name: '张三',
                email: 'zhangsan@example.com',
                level: 'beginner',
                registeredAt: new Date().toISOString(),
                lastActiveAt: new Date().toISOString(),
                totalStudyHours: 8,
                completedTopics: ['frontend-basics'],
                currentTopic: 'development-environment',
                learningPath: 'beginner_path',
                preferences: {
                    resourceType: 'mixed', // video, text, mixed
                    studyTime: 'evening', // morning, afternoon, evening
                    difficulty: 'gradual' // fast, gradual, slow
                },
                statistics: {
                    totalQuizzesTaken: 2,
                    totalQuizzesPassed: 1,
                    averageScore: 85,
                    weakTopics: ['vue-template-directives'],
                    strongTopics: ['frontend-basics'],
                    studyStreak: 5
                }
            },
            {
                id: 'student_002',
                studentId: 'S002',
                name: '李四',
                email: 'lisi@example.com',
                level: 'intermediate',
                registeredAt: new Date().toISOString(),
                lastActiveAt: new Date().toISOString(),
                totalStudyHours: 15,
                completedTopics: ['frontend-basics', 'development-environment', 'vue-transition'],
                currentTopic: 'vue-template-directives',
                learningPath: 'beginner_path',
                preferences: {
                    resourceType: 'video',
                    studyTime: 'morning',
                    difficulty: 'fast'
                },
                statistics: {
                    totalQuizzesTaken: 4,
                    totalQuizzesPassed: 3,
                    averageScore: 92,
                    weakTopics: ['development-environment'],
                    strongTopics: ['frontend-basics', 'vue-transition'],
                    studyStreak: 10
                }
            }
        ];
        
        this.knowledgeGraph.students = students;
        this.knowledgeGraph.metadata.total_students = students.length;
    }

    /**
     * 生成学生学习状态关系
     */
    generateStudentRelationships() {
        this.knowledgeGraph.students.forEach(student => {
            // 为每个学生生成与Topic的学习状态关系
            this.knowledgeGraph.topics.forEach(topic => {
                // 根据学生的学习进度生成不同的关系
                if (student.statistics.strongTopics.includes(topic.id)) {
                    // 已完成的Topic
                    this.knowledgeGraph.relationships.push({
                        type: 'COMPLETED',
                        from: student.id,
                        to: topic.id,
                        fromLabel: 'Student',
                        toLabel: 'Topic',
                        properties: {
                            completedAt: '2024-01-20T10:00:00Z',
                            score: 90,
                            timeSpent: 120 // 分钟
                        }
                    });
                } else if (student.statistics.weakTopics.includes(topic.id)) {
                    // 正在学习但有困难的Topic
                    this.knowledgeGraph.relationships.push({
                        type: 'STUDYING',
                        from: student.id,
                        to: topic.id,
                        fromLabel: 'Student',
                        toLabel: 'Topic',
                        properties: {
                            startedAt: '2024-01-18T09:00:00Z',
                            progress: 0.6,
                            attempts: 2
                        }
                    });
                }
            });
            
            // 为学生生成与Quiz的关系
            this.knowledgeGraph.quizzes.forEach(quiz => {
                if (student.statistics.strongTopics.includes(quiz.topicId)) {
                    // 通过的测验
                    this.knowledgeGraph.relationships.push({
                        type: 'PASSED',
                        from: student.id,
                        to: quiz.id,
                        fromLabel: 'Student',
                        toLabel: 'Quiz',
                        properties: {
                            score: 85,
                            maxScore: 100,
                            attempts: 1,
                            completedAt: '2024-01-20T11:00:00Z',
                            timeSpent: 15 // 分钟
                        }
                    });
                } else if (student.statistics.weakTopics.includes(quiz.topicId)) {
                    // 尝试但未通过的测验
                    this.knowledgeGraph.relationships.push({
                        type: 'ATTEMPTED',
                        from: student.id,
                        to: quiz.id,
                        fromLabel: 'Student',
                        toLabel: 'Quiz',
                        properties: {
                            score: 65,
                            maxScore: 100,
                            attempts: 2,
                            lastAttemptAt: '2024-01-19T14:00:00Z',
                            timeSpent: 20
                        }
                    });
                }
            });
            
            // 学生与学习路径的关系
            this.knowledgeGraph.relationships.push({
                type: 'ENROLLED_IN',
                from: student.id,
                to: student.learningPath,
                fromLabel: 'Student',
                toLabel: 'LearningPath',
                properties: {
                    enrolledAt: student.registeredAt,
                    progress: student.completedTopics.length / this.knowledgeGraph.topics.length,
                    currentStep: student.completedTopics.length + 1
                }
            });
        });
    }

    /**
     * 生成关系数据
     */
    generateRelationships() {
        // 添加Topic之间的前置依赖关系
        this.knowledgeGraph.topics.forEach(topic => {
            if (topic.prerequisites && topic.prerequisites.length > 0) {
                topic.prerequisites.forEach(prereqId => {
                    this.knowledgeGraph.relationships.push({
                        type: 'REQUIRES',
                        from: topic.id,
                        to: prereqId,
                        fromLabel: 'Topic',
                        toLabel: 'Topic',
                        properties: {
                            strength: 'mandatory'
                        }
                    });
                });
            }
            
            // 添加Topic到Level的关系
            this.knowledgeGraph.relationships.push({
                type: 'BELONGS_TO',
                from: topic.id,
                to: topic.level,
                fromLabel: 'Topic',
                toLabel: 'Level'
            });
            
            // 添加Topic到Resource的关系
            if (topic.resources && topic.resources.length > 0) {
                topic.resources.forEach(resource => {
                    this.knowledgeGraph.relationships.push({
                        type: 'HAS_RESOURCE',
                        from: topic.id,
                        to: resource.id,
                        fromLabel: 'Topic',
                        toLabel: 'Resource'
                    });
                });
            }
            
        });
        
        // Subtopic到Topic的关系已在解析过程中创建，无需重复添加
        
        // 添加学习路径相关关系
        this.knowledgeGraph.learning_paths.forEach(path => {
            path.sequence.forEach((topicId, index) => {
                this.knowledgeGraph.relationships.push({
                    type: 'HAS_STEP',
                    from: path.id,
                    to: `step_${path.id}_${index}`,
                    fromLabel: 'LearningPath',
                    toLabel: 'PathStep',
                    properties: {
                        order: index + 1
                    }
                });
                
                this.knowledgeGraph.relationships.push({
                    type: 'COVERS',
                    from: `step_${path.id}_${index}`,
                    to: topicId,
                    fromLabel: 'PathStep',
                    toLabel: 'Topic'
                });
            });
        });
    }

    /**
     * 生成学习路径
     */
    generateLearningPaths() {
        const beginnerPath = {
            id: 'beginner_path',
            name: '初学者路径',
            description: '适合零基础学习者的完整学习路径',
            difficulty: 'beginner',
            sequence: [
                'frontend-basics',
                'development-environment',
                'vue-transition',
                'vue-template-directives'
            ],
            estimated_total_hours: this.knowledgeGraph.topics.reduce((total, topic) => 
                total + (topic.estimated_hours || 0), 0),
            prerequisites: [],
            tags: ['vue', 'frontend', 'beginner']
        };
        
        this.knowledgeGraph.learning_paths.push(beginnerPath);
        
        // 为学习路径生成步骤节点
        beginnerPath.sequence.forEach((topicId, index) => {
            const step = {
                id: `step_${beginnerPath.id}_${index}`,
                pathId: beginnerPath.id,
                topicId: topicId,
                order: index + 1,
                title: this.knowledgeGraph.topics.find(t => t.id === topicId)?.name || `步骤 ${index + 1}`,
                description: `学习路径第${index + 1}步`,
                status: 'pending'
            };
            
            // 将步骤添加到assessments数组中（作为PathStep节点）
            this.knowledgeGraph.assessments.push({
                ...step,
                type: 'path_step'
            });
        });
    }

    /**
     * 生成评估测试
     */
    generateAssessments() {
        // 为每个知识点生成基础测试
        this.knowledgeGraph.topics.forEach(topic => {
            const assessment = {
                topic_id: topic.id,
                type: 'quiz',
                difficulty: topic.difficulty,
                passing_score: topic.difficulty <= 2 ? 60 : 70,
                questions: this.generateQuestionsForTopic(topic)
            };
            
            this.knowledgeGraph.assessments.push(assessment);
        });
    }

    /**
     * 为知识点生成Quiz
     */
    generateQuizForTopic(topic) {
        const quiz = {
            id: `quiz_${topic.id}`,
            topicId: topic.id,
            title: `${topic.name} - 知识检测`,
            description: `测试您对${topic.name}的掌握程度`,
            passingScore: topic.difficulty <= 2 ? 60 : 70,
            timeLimit: 300, // 5分钟
            maxAttempts: 3,
            questions: this.generateQuestionsForTopic(topic),
            difficulty: topic.difficulty,
            tags: [topic.level, topic.name]
        };
        
        return quiz;
    }

    /**
     * 为知识点生成问题
     */
    generateQuestionsForTopic(topic) {
        const questions = [];
        
        // 基础概念问题
        questions.push({
            id: `${topic.id}_q1`,
            text: `${topic.name}的主要作用是什么？`,
            type: 'single_choice',
            options: [
                topic.description,
                '数据存储和管理',
                '服务器端处理',
                '数据库设计'
            ],
            correct: 0,
            explanation: `${topic.name}的主要作用是：${topic.description}`,
            points: 10
        });
        
        // 根据知识点类型生成特定问题
        if (topic.id === 'frontend-basics') {
            questions.push({
                id: `${topic.id}_q2`,
                text: 'HTML、CSS、JavaScript三者的关系是什么？',
                type: 'single_choice',
                options: [
                    'HTML负责结构，CSS负责样式，JavaScript负责交互',
                    'HTML负责样式，CSS负责结构，JavaScript负责数据',
                    'HTML负责交互，CSS负责结构，JavaScript负责样式',
                    '三者功能完全相同'
                ],
                correct: 0,
                explanation: 'HTML负责页面结构，CSS负责样式美化，JavaScript负责交互逻辑',
                points: 15
            });
        }
        
        if (topic.id === 'development-environment') {
            questions.push({
                id: `${topic.id}_q2`,
                text: 'Vue.js开发环境搭建需要安装哪个核心工具？',
                type: 'single_choice',
                options: [
                    'Node.js',
                    'Python',
                    'Java',
                    'PHP'
                ],
                correct: 0,
                explanation: 'Vue.js开发需要Node.js环境来运行npm包管理器和构建工具',
                points: 10
            });
        }
        
        if (topic.id === 'vue-transition') {
            questions.push({
                id: `${topic.id}_q2`,
                text: 'Vue.js的核心特性不包括以下哪项？',
                type: 'single_choice',
                options: [
                    '数据库管理',
                    '响应式数据绑定',
                    '组件化开发',
                    '虚拟DOM'
                ],
                correct: 0,
                explanation: 'Vue.js是前端框架，不负责数据库管理，主要特性包括响应式数据绑定、组件化开发和虚拟DOM',
                points: 15
            });
        }
        
        // 如果是Vue指令相关，添加特定问题
        if (topic.directives && topic.directives.length > 0) {
            const directive = topic.directives[0];
            questions.push({
                id: `${topic.id}_q2`,
                text: `${directive.name}指令的作用是什么？`,
                type: 'single_choice',
                options: [
                    directive.description,
                    '样式控制',
                    '数据存储',
                    '路由跳转'
                ],
                correct: 0,
                explanation: `${directive.name}指令的作用是：${directive.description}`,
                points: 15
            });
            
            // 添加实践题
            questions.push({
                id: `${topic.id}_q3`,
                text: '以下哪个是正确的Vue指令语法？',
                type: 'single_choice',
                options: [
                    'v-if="condition"',
                    'if="condition"',
                    'vue-if="condition"',
                    '@if="condition"'
                ],
                correct: 0,
                explanation: 'Vue指令以v-开头，如v-if、v-for、v-model等',
                points: 10
            });
        }
        
        return questions;
    }

    /**
     * 处理所有Markdown文件
     */
    processAllMarkdownFiles(directory) {
        console.log('开始处理Markdown文件...');
        
        // 初始化层级
        this.initializeLevels();
        
        // 获取所有Markdown文件
        const files = fs.readdirSync(directory)
            .filter(file => file.endsWith('.md') && this.levelMapping[file])
            .sort(); // 按文件名排序确保处理顺序
        
        console.log(`找到 ${files.length} 个Markdown文件:`, files);
        
        // 处理每个文件
        files.forEach(file => {
            const filePath = path.join(directory, file);
            this.parseMarkdownFile(filePath);
        });
        
        // 生成示例学生数据
        this.generateSampleStudents();
        
        // 生成学习路径
        this.generateLearningPaths();
        
        // 生成关系数据
        this.generateRelationships();
        
        // 生成学生学习状态关系
        this.generateStudentRelationships();
        
        // 更新元数据
        this.knowledgeGraph.metadata.total_topics = this.knowledgeGraph.topics.length;
        this.knowledgeGraph.metadata.total_subtopics = this.knowledgeGraph.subtopics.length;
        this.knowledgeGraph.metadata.total_knowledge_points = this.knowledgeGraph.knowledge_points.length;
        this.knowledgeGraph.metadata.total_concepts = this.knowledgeGraph.concepts.length;
        this.knowledgeGraph.metadata.total_quizzes = this.knowledgeGraph.quizzes.length;
        this.knowledgeGraph.metadata.total_relationships = this.knowledgeGraph.relationships.length;
        
        // 生成评估
        this.generateAssessments();
        
        console.log('处理完成!');
        console.log(`总计: ${this.knowledgeGraph.levels.length} 个层级, ${this.knowledgeGraph.topics.length} 个知识点`);
    }

    /**
     * 保存JSON文件
     */
    saveToJson(outputPath) {
        try {
            const jsonContent = JSON.stringify(this.knowledgeGraph, null, 2);
            fs.writeFileSync(outputPath, jsonContent, 'utf8');
            console.log(`JSON文件已保存到: ${outputPath}`);
            console.log(`文件大小: ${(jsonContent.length / 1024).toFixed(2)} KB`);
        } catch (error) {
            console.error('保存JSON文件时出错:', error.message);
        }
    }

    /**
     * 验证生成的JSON数据
     */
    validateJson() {
        const errors = [];
        
        // 检查必需字段
        if (!this.knowledgeGraph.levels || this.knowledgeGraph.levels.length === 0) {
            errors.push('缺少层级数据');
        }
        
        if (!this.knowledgeGraph.topics || this.knowledgeGraph.topics.length === 0) {
            errors.push('缺少知识点数据');
        }
        
        // 检查知识点的前置依赖是否存在
        const topicIds = new Set(this.knowledgeGraph.topics.map(t => t.id));
        this.knowledgeGraph.topics.forEach(topic => {
            if (topic.prerequisites) {
                topic.prerequisites.forEach(prereq => {
                    if (!topicIds.has(prereq)) {
                        errors.push(`知识点 ${topic.id} 的前置依赖 ${prereq} 不存在`);
                    }
                });
            }
        });
        
        if (errors.length > 0) {
            console.warn('JSON验证发现问题:');
            errors.forEach(error => console.warn(`- ${error}`));
        } else {
            console.log('JSON验证通过!');
        }
        
        return errors.length === 0;
    }
}

// 使用示例
if (require.main === module) {
    const converter = new MarkdownToJsonConverter();
    const inputDirectory = path.join(__dirname, '..', 'raw_kg'); // raw_kg目录
    const outputPath = path.join(__dirname, 'generated-vue-knowledge-graph.json');
    
    try {
        // 处理所有Markdown文件
        converter.processAllMarkdownFiles(inputDirectory);
        
        // 验证数据
        if (converter.validateJson()) {
            // 保存JSON文件
            converter.saveToJson(outputPath);
            console.log('\n转换完成! 可以使用以下命令安装依赖:');
            console.log('npm install marked');
            console.log('\n然后运行:');
            console.log('node markdown-to-json-converter.js');
        } else {
            console.error('数据验证失败，请检查错误信息');
        }
    } catch (error) {
        console.error('转换过程中出错:', error.message);
    }
}

module.exports = MarkdownToJsonConverter;